<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\BaseController;
use app\common\EncryptKeys;
use app\service\ContentsService;
use app\service\DepartmentService;
use app\service\ProjectService;
use app\service\RoleService;
use app\service\UserService;
use think\facade\Validate;
use think\Request;

class UserController extends BaseController
{
    /**
     * 显示用户列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', env('pager.default.size'));
      $role = $request->param('role', []);
      $departmentId = $request->param('department_id', []);
      $projectId = $request->param('project_id', '');
      $conditions = [];
      if($role){
        $conditions[] = ['role_id', $role, 'IN'];
      }
      if ($projectId) {
        // 获取项目
        $proCond = [
          ['status', 0, '<>'],
          ['id', $projectId, '=']
        ];
        $project = ProjectService::getInstance()->getProjectByCondition($proCond);
        $project = $project[0];
        $usersId = explode(',', $project['project_user_ids']);
        if ($usersId) {
          $conditions[] = ['id', $usersId, 'IN'];
        } else {
          $conditions[] = ['id', 0, '='];
        }
      }
      $list = UserService::getInstance()->getUserByCondition($conditions);
      // 角色权限
      $roleAuthList = [];
      $roleAuth = RoleService::getInstance()->getAuthByRole();
      foreach ($roleAuth as $rv) {
        $roleAuthList[$rv['role_id']][] = $rv['authname'];
      }
      // 获取特殊权限
      $authList = RoleService::getInstance()->getAuthByCondition([['status', 1, '=']]);
      $authList = array_column($authList, null, 'id');
      // 获取部门
      $departmentList = DepartmentService::getInstance()->getDepartmentByCondition([], ['id' => 'asc']);
      // 获取用户关联的部门
      $userPart = [];
      foreach ($departmentList as $dv) {
        $userList = explode(',', $dv['user_ids']);
        foreach ($userList as $uv) {
          $userPart[$uv][] = $dv['id'];
        }
      }
      foreach ($list as $key => &$value) {
        if ($departmentId && !(isset($userPart[$value['id']]) && array_intersect($departmentId,$userPart[$value['id']]))) {
          unset($list[$key]);
          continue;
        }
        $value['auth_ids'] = $value['auth_ids'] ? explode(',', $value['auth_ids']) : [];
        $value['auths'] = [];
        if ($value['auth_ids']) {
          foreach ($value['auth_ids'] as $v) {
            if (isset($authList[$v])) {
              $value['auths'][] = $authList[$v]['authname'];
            }
          }
        }
        if (isset($value['role_id']) && isset($roleAuthList[$value['role_id']])) {
          $value['auths'] = array_merge($value['auths'], $roleAuthList[$value['role_id']]);
        }
      }
      // 分页
      $count = count($list); //总条数
      $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalCount' => $count,
        'pageSize' => intval($pageSize),
        'currPage' => intval($page),
        'totalPage' => intval($count/$pageSize)+1
      ];
      $data = array_slice($list, $start, intval($pageSize));
      return $this->send200ResponseWithPager($data,$pager);
    }

    /**
     * 保存新用户
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 获取用户
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
      $list = UserService::getInstance()->getUserJoinRoleCondition([['u.id', 1, '=']]);
      $user = [];
      if (!isset($list[0])) {
        return $this->send400Response('用戶不存在');
      }
      $user = $list[0];
      // 获取部门
      $departmentList = DepartmentService::getInstance()->getDepartmentByCondition([], ['id' => 'asc']);
      // 获取用户关联的部门
      $userPart = [];
      foreach ($departmentList as $value) {
        $userList = explode(',', $value['user_ids']);
        foreach ($userList as $v) {
          $userPart[$v][] = [
            'id' => $value['id'],
            'name' => $value['department_name']
          ];
        }
      }
      $user['department'] = isset($userPart[$id]) ? $userPart[$id] : [];
      return $this->send200Response($user);
    }

    /**
     * 更新用户
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除用户
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    /**
     * 登录
     */
    public function login(Request $request)
    {
      $data = $request->param();
      $validate = Validate::rule([
        'username' => 'require',
        'password' => 'require',
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      $conditions = [
        ['username', trim($data['username']), '=']
      ];
      $user = UserService::getInstance()->getUserByCondition($conditions);
      $user = $user ? $user[0] : [];
      if (!$user) {
        return $this->send400Response('用户不存在');
      }
      if (md5($data['password']) !== $user['password']) {
        return $this->send400Response('用户密码有误');
      }
      $flag = 0;
      // 获取部门
      $departmentList = DepartmentService::getInstance()->getDepartmentByCondition([], ['id' => 'asc']);
      // 获取用户关联的部门
      $userPart = [];
      foreach ($departmentList as $dv) {
        $userList = explode(',', $dv['user_ids']);
        foreach ($userList as $uv) {
          $userPart[$uv][] = $dv['id'];
        }
      }
      // 是否只有一个关联部门
      if (count($userPart[$user['id']]) <= 1) {
        $flag = 1;
      }
      // 获取角色
      $role = RoleService::getInstance()->getRoleByCondition([['id', $user['role_id'], '=']]);
      $role = $role ? $role[0] : [];
      $contents = explode(',', $role['contents_ids']);
      // 获取目录列表
      $contentsList = ContentsService::getInstance()->getContentsByCondition([['id', $contents, 'IN']], ['id' => 'ASC']);
      //获取目录
      $accessList = ContentsService::getInstance()->getSubs($contentsList, 0, 1, $contents);
      // 获取权限
      $authList = RoleService::getInstance()->getAuthByRole([['ar.role_id', $role['id'], '=']]);
      if ($user['auth_ids']) {
        $arr = explode(',', $user['auth_ids']);
        $authList2 = RoleService::getInstance()->getAuthByCondition([['id', $arr, 'IN']]);
        $authList = array_merge($authList, $authList2);
      }
      $auths = array_column($authList, 'authname');
      if (!$flag && in_array('show-user', $auths)) {
        $auths[] = 'change_department';
      }

      // 获取token
      $access_token = EncryptKeys::autoSSOEncryptKen();
      $data = [
        'id' => $user['id'],
        'username' => $user['username'],
        'role_id' => $user['role_id'],
        'rolename' => $role['rolename'],
        'auths' => $auths,
        'access_token' => $access_token,
        'access' => array_values($accessList)
      ];
      return $this->send200Response($data);
    }

    public function loginPasswd(Request $request){
      $data = $request->param();
      $validate = Validate::rule([
        'password' => 'require',
        'newPassword' => 'require',
        'passwordCheck' => 'require',
        'username' => 'require'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      if (md5($data['newPassword']) !== md5($data['passwordCheck'])) {
        return $this->send400Response('确认密码不一致');
      }
      // 获取用户
      $user = UserService::getInstance()->getUserByCondition([['username', $data['username'], '=']]);
      if ($user) {
        $user = $user[0];
      }
      if ($user['password'] !== md5($data['password'])) {
        return $this->send400Response('密码有误');
      }
      $update = [
        'password' => md5($data['newPassword']),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
      $res = UserService::getInstance()->updateUser($user['id'], $update);
      if (!$res) {
        return $this->send400Response('修改密码失败');
      }
      return $this->send200Response('ok');
    }

    /**
     * @Name 用戶任务统计
     * @Description
     * @Author zsx
     * @Date 2023/3/1 16:26
     * @Method GET
     * @Return JSON
     **/
    public function userTask(Request $request) {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', env('pager.default.size'));
      $departmentId = $request->param('department_id', []);
      $isCheck = $request->param('is_check', 0);
      $checkUser = $request->param('check_user', 0);
      $conditions = [];
      $list = [];
      if ($departmentId) {
        $conditions[] = ['id', $departmentId, 'IN'];
      }
      // 获取部门
      $departmentList = DepartmentService::getInstance()->getDepartmentByCondition($conditions, ['id' => 'asc']);
      // 搜索的用户
      $userId = array_column($departmentList, 'user_ids', 'id');
      $userId = array_unique(explode(',', implode(',', $userId)));
      $res = UserService::getInstance()->getUserJoinTaskCondition([['u.id', $userId, 'IN']]);
      foreach ($res as $value) {
        if (!isset($list[$value['id']])) {
          $list[$value['id']] = [
            'id' => $value['id'],
            'truename' => $value['truename'],
            'task_count' => 0, // 任务数量
            'complete' => 0, // 完成
            'state' => 0, // 暂缓
            'check' => 0, // 检查中
            'dev' => 0, // 开发中
            'wait' => 0, // 未开始
          ];
        }
        if (!$value['status'] || !$value['project_status']) {
          continue;
        }
        // 如果需要检查
        if ($isCheck) {
          // 如果为纯检查员 且 任务不需要检查
          if (!$checkUser && !$value['is_check']) {
            continue;
          }
          // 如果为开发检查员 且 任务不需要检查 且任务不是自己的任务
          else if ($checkUser && !$value['is_check'] && $checkUser != $value['task_user_id']) {
            continue;
          }
        }
        // 已完成
        if ($value['status'] === 2) {
          $list[$value['id']]['complete']++;
        }
        // 暂缓
        else if ($value['dev_status'] === 3) {
          $list[$value['id']]['state']++;
        }
        // 检查中
        else if ($value['dev_status'] === 4 && $value['check_status'] === 1) {
          $list[$value['id']]['check']++;
        }
        // 开发中
        else if ($value['dev_status'] === 2) {
          $list[$value['id']]['dev']++;
        }
        // 未开始
        else if ($value['dev_status'] === 1) {
          $list[$value['id']]['wait']++;
        }
        if ($value['task_id']) {
          $list[$value['id']]['task_count']++;
        }
      }

      // 分页
      $count = count($list); //总条数
      $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalCount' => $count,
        'pageSize' => intval($pageSize),
        'currPage' => intval($page),
        'totalPage' => intval($count/$pageSize)+1
      ];
      $data = array_slice($list, $start, intval($pageSize));
      return $this->send200ResponseWithPager($data,$pager);
    }
}
